import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, FlatList, Image, Animated, TouchableOpacity } from "react-native";
import { GLOBAL } from '../../../config/global';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import FeatherIcon from 'react-native-vector-icons/Feather';
import { ItemCpt } from './_components/ItemCpt';
import serviceAPI from './_common/serviceAPI';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { FilterCpt } from './_components/FilterCpt'; // 企业认领申请列表
import Dictionary from '../../../utils/dictionary';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';
const scale = GLOBAL.SCALE;

export class SeasListPage extends Component {
	static navigationOptions = {
		header: null
	}

	constructor(props) {
		super(props);
		const { choice } = this.props.navigation.state.params || {};
		this.state = {
			status: 'loading',
			listData: [{}],
			refreshIcon: false, // 下拉刷新图标
			rightObj: new Animated.Value(-375 * scale),
			onOffAnimated: true,
			alertShow: false,
			options: [],
			choice: choice || {}
		}
		this.pageParams = {
			isPage: 0,
			pageNo: 1,
			bizType: 'COMPANY_GOODS_INFO',
			searchKey: null
		};
		this.goodsClassData = null;
		this.fileData = {};
		this.reload = true;
	}

	async componentWillMount() {
		await this.getSorage();
		await this._initPage();
		await this._getGoodsClass();
		await this._Dictionary();
		this.setState({ ls: true });
	}
	//获取业务组织
	async	getSorage() {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
	}

	_initPage = async (sendData) => {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == 1,
			listData: this.search ? [] : this.state.listData
		})
		if (sendData) {
			for (var name in sendData) {
				console.log('name', name)
				this.pageParams[name] = sendData[name];
			}
			//	Object.assign(this.pageParams, sendData);
		}
		this.pageParams.corpId = this.state.choice.corpId;
		console.log('获取参数', this.pageParams)
		let res = await serviceAPI.getSeasList(this.pageParams);
		this.search = false;
		if (res && res.rows) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	// 合作关系数据字典 
	_Dictionary = async () => {
		let corpResult = await Dictionary.get("EC_CORP_TYPE");
		this.corpResult = corpResult || [];
	}

	//产品分类列表
	_getGoodsClass = async () => {
		this.pageParams.corpId = this.state.choice.corpId;
		let res = await serviceAPI.getGoodsClass(this.pageParams);
		this.goodsClassData = res || [];
	}


	_returnItem = (data) => {
		return <ItemCpt data={data.item} choice={this.state.choice} />
	}

	_refresh = (callData) => {
		this.pageParams.pageNo = 1;
		if (this.totalPage >= this.pageParams.pageNo) {
			this.reload = false;
		}
		this._initPage(callData || null);
	}

	// 上拉翻页
	_loadMore = () => {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this._initPage();
		}
	}

	_onErrorRefresh = () => {
		this._initPage();
	}

	// 动画
	_startAnimated = callData => {
		let { rightObj, onOffAnimated } = this.state;
		console.log('callData-file-回调', callData);
		this.fileData = callData || {};
		if (onOffAnimated) {
			Animated.timing(rightObj, { toValue: 0, duration: 300, }).start(() => { this.setState({ onOffAnimated: false }) });
		} else {
			Animated.timing(rightObj, { toValue: -375 * scale, duration: 300 }).start(() => { this.setState({ onOffAnimated: true }, () => { this._refresh(callData); }) })
		}
	}


	render() {
		let { status, listData, refreshIcon, rightObj, onOffAnimated, alertShow, choice, options } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.headBox}>
					<View style={styles.topBox}>
						<Common type="headLeft" onPress={() => { navigationSeevice.navigate('CrMtManage') }} color='#fff' />
						<Text style={styles.topTitle}>客户公海</Text>
						<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />
					</View>
					{options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}

					<View style={styles.searchBox}>
						<View style={styles.search}>
							<Image source={require('../../../imgs/global/whiteSearch.png')} style={styles.searchIcon} />
							<TextInput
								style={styles.searchInput}
								underlineColorAndroid='transparent'
								placeholder={"请输入客户名称/产品"}
								placeholderTextColor="rgba(255, 255, 255,1)"
								maxLength={30}
								returnKeyType={'search'}
								defaultValue={this.pageParams.searchKey}
								onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
								onSubmitEditing={() => { this.pageParams.pageNo = 1; this.search = true; this.reload = true; this._initPage(); }}
							/>
						</View>
						<FeatherIcon onPress={() => { this._startAnimated() }} name='filter' style={styles.searchFilter} />
					</View>
				</View>
				<View style={styles.box}>
					{
						status == 'data' ? <FlatList
							data={listData}
							renderItem={
								this._returnItem
							}
							refreshing={refreshIcon}
							onRefresh={() => { this._refresh() }}
							onEndReachedThreshold={1}
							onEndReached={() => { this._loadMore() }}
						/> : <PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this._onErrorRefresh} />
					}

				</View>
				{!onOffAnimated ? <TouchableOpacity style={styles.filterBox} onPress={() => { this._startAnimated(); }}></TouchableOpacity> : null}
				<Animated.View style={[styles.filter, { right: rightObj }]}>
					<FilterCpt fileData={this.fileData} onoffFn={this._startAnimated} corpResultData={this.corpResult} goodsClassData={this.goodsClassData} />
				</Animated.View>

				<SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this._refresh();
							this._getGoodsClass();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</View >
		)
	}
}


const styles = StyleSheet.create({
	container: {
		flex: 1,
		position: 'relative',
		backgroundColor: style.color.bgGray
	},
	topBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	headBox: {
		paddingTop: 30 * scale,
		height: 160 * scale,
		backgroundColor: style.color.themeColor
	},
	topTitle: {
		fontSize: 18 * scale,
		color: '#fff'
	},
	searchBox: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		marginTop: 17 * scale
	},
	search: {
		flexDirection: 'row',
	},
	searchInput: {
		height: 37 * scale,
		width: 253 * scale,
		paddingLeft: 70 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 18 * scale,
		height: 18 * scale,
		position: 'absolute',
		left: 24 * scale,
		top: 10 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	searchFilter: {
		fontSize: 25 * scale,
		color: '#fff',
		marginLeft: 17 * scale,
	},
	box: { flex: 1, justifyContent: 'center', alignItems: 'center' },
	filter: {
		position: 'absolute', height: '100%', width: '100%', width: -290 * scale
	},
	filterBox: { position: 'absolute', height: '100%', right: 0, backgroundColor: 'rgba(0, 0, 0, .3)', width: '100%' },
})